<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Validate;

class GoodsSpecs extends Model
{
	use \base\model\ModelTrait;
	
	//规格商品，一对一关联 
	public function goods(){
        return $this->hasOne('Goods','id','goods_id');
    }
	
	//规格库存，一对多关联 
	public function stocks(){
        return $this->hasMany('GoodsSpecsStock','specs_id');
    }
	
	//规格礼包，一对多关联 
	public function gifts(){
        return $this->hasMany('GoodsSpecsGift','specs_id');
    }	
	
	//规格收益，一对多关联 
	public function profits(){
        return $this->hasMany('GoodsSpecsProfit','specs_id');
    }	
		
		

	/**
     * 获取库存
     * @param $id
     * @param string $field
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getStock($id,$shopId)
    {
    	return self::where('id',$id)->stocks()->where('shop_id',$shopId)->value('stock');
    }
	
	/**
     * 减库存
     * @param int $num
     * @param int $seckillId
     * @return bool
     */
    public  function decStock($id=0,$shopId,$num = 0)
    {
    	if( !$specs = self::get($id) ){
    		return false;
    	}
    	$res = $specs->stocks()->where('shop_id',$shopId)->dec('stock', $num)->update();
    	$res = $res && $specs->goods()->inc('sales', $num)->update();
    	if($res){
    		$specs->sales = ['inc',$num];
    		return $specs->save();
    	}
    	return false;
    }

    /**
     * 增加库存较少销量
     * @param int $num
     * @param int $seckillId
     * @return bool
     */
    public  function incStock($id= 0,$shopId,$num = 0)
    {
    	if( !$specs = self::get($id) ){
    		return false;
    	}
    	$res = $specs->stocks()->where('shop_id',$shopId)->inc('stock', $num)->update();
    	if($specs->goods->sales >= $num){
    		$res = $res && $specs->goods()->dec('sales', $num)->update();
    	}
    	if($res){
    		$specs->sales = ['dec',$num];
    		return $specs->save();
    	}
    	return false;
    }
	
}
